<template>
	<view class="index-content">
		<rf-navbar :back="false" src="../../static/images/observe/add-observe-bg_top.png"></rf-navbar>
		<view class="information-top">
			<image class="bg-bottom" :style="{top:navBarHeight}"
				src="../../static/images/observe/add-observe-bg_bottom.png"></image>
		</view>
		<view class="index-top">

			<view class="top-flex">

				<view class="head" v-if="hasLogin">
					<!-- 头像 -->
					<image class="logo" :class="{'icon-default-avatar':!userInfo.avatar}" :src="userInfo.avatar"
						mode="aspectFill" @click="loginFn"></image>
					<view class="info">
						<view class="title">{{userInfo.name}}</view>
						<view class="cid" @click="copyBtn(userInfo.id)">超级小助教号：{{userInfo.id}}</view>
					</view>
					<view class="arrow" @click="loginFn">
						<u-icon name="arrow-right" bold color="#000"></u-icon>
					</view>
				</view>
				<view class="head" v-else @click="loginFn">
					<image class="logo icon-default-avatar" mode="aspectFill"></image>
					<view class="info">
						<view class="title">请登录</view>
					</view>
					<view class="arrow">
						<u-icon name="arrow-right" bold color="#000"></u-icon>
					</view>
				</view>

			</view>
			<!-- 开通会员 -->
			<view class="top-openMember">
				<view class="left" v-if="hasLogin">
					<view style="display: flex;align-items: center;">
						<view class="left-icon icon-crown"></view>
						<view class="left-title" v-if="userInfo.memberType==0">普通会员</view>
						<view class="left-title" v-else-if="userInfo.memberType==1">VIP会员</view>
					</view>
					<view class="left-text" v-if="userInfo.memberType==0">开通会员享有更多权益</view>
					<view class="left-text" v-else-if="userInfo.memberType==1">
						有效期至 {{ userInfo.memberExpirationDate }}</view>
				</view>
				<view class="openMember-left" style="display: flex; align-items: center;" v-else>
					<view class="left-icon icon-crown"></view>
					<view class="left-text">开通会员享有更多权益</view>
				</view>
				<view class="right">
					<view class="invitation" @tap="inviteAction">邀请函</view>
					<view class="openMember" @tap="vipFn" v-if="userInfo.memberType==1">立即续费</view>
					<view class="openMember" @tap="vipFn" v-else>开通会员</view>
				</view>
			</view>
			<!-- 我的勋章 成长值-->
			<view class="top-myMedal">
				<view class="myMedal-left" @click="badgeFn">
					<view class="left-text">
						<view class="left-textTop">{{badgeName?badgeName:"暂无勋章"}}</view>
						<view class="left-textBom">我的勋章</view>
					</view>
				</view>
				<view class="myMedal-right" @click="growth">
					<view class="right-text">
						<view class="right-textTop">{{userInfo.growthValue?userInfo.growthValue:"暂无成长值"}}</view>
						<view class="right-textBom">成长值</view>
					</view>
				</view>
			</view>
			<view style="padding: 0 32rpx; height: 120rpx; background-color: #fff;" @click="vipFn">
				<image src="../../static/images/home/guanggao.png" style="width: 100%; height: 100%;"></image>
			</view>
		</view>
		<view class="index-list">
			<!-- 			<view class="list-content">
				<view class="item"></view>
			</view> -->

			<navigator url="/pages-sub/childShare/childShare">
				<view class="list-item">
					<image class="icon icon-user"></image>
					<view class="text">孩子共管</view>
					<view class="right">
						<u-icon name="arrow-right" bold color="#000"></u-icon>
					</view>
				</view>
			</navigator>
			<view class="list-item" @click="transmit">
				<image class="icon icon-care"></image>
				<view class="text">孩子转交</view>
				<view class="right">
					<u-icon name="arrow-right" bold color="#000"></u-icon>
				</view>
			</view>
			<navigator url="/pages-sub/mdocuments/mdocuments">
				<view class="list-item" style="border: none; margin-bottom: 20rpx">
					<image class="icon icon-word-gray"></image>
					<view class="text">我的文档</view>
					<view class="right">
						<u-icon name="arrow-right" bold color="#000"></u-icon>
					</view>
				</view>
			</navigator>
			<!-- <navigator url="/pages-sub/courseWord/courseWord">
				<view class="list-item" style="border: none; margin-bottom: 20rpx">
					<image class="icon icon-word-edit"></image>
					<view class="text">我的教案</view>
					<view class="right">
						<u-icon name="arrow-right" bold color="#000"></u-icon>
					</view>
				</view>
			</navigator> -->

			<view class="list-item" @click="sysNoticeFn">
				<image class="icon icon-notice"></image>
				<view class="text">系统公告</view>
				<view class="right">
					<u-icon name="arrow-right" bold color="#000"></u-icon>
				</view>
			</view>
			<view class="list-item" @click="invoiceFn">
				<image class="icon icon-bill"></image>
				<view class="text">开发票</view>
				<view class="right">
					<u-icon name="arrow-right" bold color="#000"></u-icon>
				</view>
			</view>
			<view class="list-item" @click="opinionFn">
				<image class="icon icon-email"></image>
				<view class="text">意见与建议</view>
				<view class="right">
					<u-icon name="arrow-right" bold color="#000"></u-icon>
				</view>
			</view>
			<view class="list-item" @click="FQAFn">
				<image class="icon icon-system"></image>
				<view class="text">常见问题</view>
				<view class="right">
					<u-icon name="arrow-right" bold color="#000"></u-icon>
				</view>
			</view>
			<view class="list-item" @click="setting">
				<image class="icon icon-set"></image>
				<view class="text">设置</view>
				<view class="right">
					<u-icon name="arrow-right" bold color="#000"></u-icon>
				</view>
			</view>
		</view>
		<privacy :isShow="isShow" @handleAgree="handleAgree" @handleClose="handleClose" @triggerEvent="triggerEvent" />
		<!-- 用户未注册 提示注册 -->
		<rf-alert :show="showRegister" @close="showRegister=false" @confirm="onClickRegister" title="提示" desc="您还未登录"
			confirmText="去登录"></rf-alert>

		<!-- 我的邀请函 -->
		<rf-invitepopup :show="invitepopupShow" v-model="InvitationCode" @close="invitepopupShow=false"
			@confirm="invitepopupConfirm"></rf-invitepopup>
		<!-- 邀请成功与否 -->
		<rf-toast :show="showWarn" :isSus="showSus" :title="warning" :des="des" @click="showWarn = false"></rf-toast>
		<rf-load :loading="loading" title="加载中..."></rf-load>
	</view>
</template>

<script>
	import privacy from '@/components/privacy.vue'
	import {
		mapState,
		mapMutations,
	} from 'vuex';

	import {
		getTeacherInfo,
		getCurrentBadge,
		useInvitation,
	} from "@/api/user.js"
	import {
		forkJoin,
		from
	} from 'rxjs';
	import {
		timeout,
		finalize,
	} from 'rxjs/operators';

	export default {
		components: {
			privacy
		},
		data() {
			return {
				navBarHeight: this.navBarHeight,
				loading: false, // 加载中提示

				inviter: "", // 邀请人id
				title: 'Hello',
				isShow: false,
				showRegister: false,

				invitepopupShow: false,
				showWarn: false,
				showSus: false,
				warning: "",
				des: "",
				InvitationCode: "", // 邀请码
			};
		},
		onLoad(options) {
			// 邀请好友字段，如果存在，注册时需要传入参数
			const shareId = options.shareId;

			if (shareId != null && shareId != undefined) {
				uni.setStorageSync("inviter_uuid", shareId)
			} else {
				uni.setStorageSync("inviter_uuid", "")
			}

		},
		beforeDestroy() {
			uni.$off('refreshMemberInfo')
		},
		mounted() {
			let that = this
			uni.$on('refreshMemberInfo', function() {
				that.getInfo()
			});
		},
		onShow() {
			// if (this.hasLogin) {
			// 	// 进行后续操作
			// 	this.getInfo()
			// }
		},
		onTabItemTap(e) {
			if (this.hasLogin) {
				// 进行后续操作
				this.getInfo()
			}
		},
		computed: {
			...mapState(['userInfo', 'hasLogin', 'badgeName'])
		},
		methods: {
			...mapMutations(["updateState", "updateUserInfo", "updateBadge"]),
			copyBtn(item) {
				let _that = this;
				wx.setClipboardData({
					//复制文本
					data: String(item),
					success: function(res) {
						wx.showToast({
							title: 'ID 复制成功',
							icon: 'none',
							mask: 'true' //是否设置点击蒙版，防止点击穿透
						});
					}
				});
			},
			alert(showSus, warning, des) {
				this.showWarn = true;
				this.showSus = showSus;
				this.warning = warning;
				this.des = des;
			},
			// 我的邀请函
			invitepopupConfirm(e) {
				console.log("-------e---" + e);

				useInvitation(this.InvitationCode).then(res => {
					this.InvitationCode = "";
					this.invitepopupShow = false;
					console.log("res" + JSON.stringify(res));
					if (res.data == 0) {
						this.alert(true, "受邀成功", "您已获得7个天VIP会员")
					} else {
						this.alert(true, "受邀成功", "您已获赠" + res.data + "月VIP会员")
					}
				}).catch(err => {
					this.alert(false, "受邀失败", err.message)
				});
			},
			// 邀请函
			inviteAction() {
				if (!this.hasLogin) {
					this.showRegister = true;
					return
				}
				this.invitepopupShow = true;
			},


			// 去登录
			onClickRegister() {
				this.showRegister = false;
				uni.navigateTo({
					url: "/pages-sub/login/login"
				})
			},
			handleAgree() {
				console.log(22222)
			},
			handleClose() {
				this.isShow = false
			},
			handleAgreePrivacyAuthorization() {
				// 用户同意隐私协议事件回调
				// 用户点击了同意，之后所有已声明过的隐私接口和组件都可以调用了
				// wx.getUserProfile()
				// wx.chooseMedia()
				// wx.getClipboardData()
				// wx.startRecord()
			},
			handleGetUserInfo(e) {
				// 获取头像昵称成功
				console.log(e)
			},
			// 系统公告
			sysNoticeFn() {
				if (!this.hasLogin) {
					this.showRegister = true;
					return
				}
				uni.navigateTo({
					url: '/pages-sub/systemnotice/systemnotice'
				})
			},
			// 开发票
			invoiceFn() {
				if (!this.hasLogin) {
					this.showRegister = true;
					return
				}
				uni.navigateTo({
					url: '/pages-sub/invoice/orderlist'
				});
			},
			// 意见与建议
			opinionFn() {
				if (!this.hasLogin) {
					this.showRegister = true;
					return
				}
				uni.navigateTo({
					url: '/pages-sub/opinion/opinion'
				});
			},
			// FAQ
			FQAFn() {
				if (!this.hasLogin) {
					this.showRegister = true;
					return
				}
				uni.navigateTo({
					url: '/pages-sub/FAQ/FAQ'
				});
			},
			// 设置
			setting() {
				if (!this.hasLogin) {
					this.showRegister = true;
					return
				}
				uni.navigateTo({
					url: '/pages-sub/set/set'
				});
			},
			// 保存
			triggerEvent(e) {
				this.loginSys(this.code, e)
			},
			// 个人信息
			loginFn() {

				if (this.hasLogin) {
					uni.navigateTo({
						url: "/pages-sub/information/information"
					});
					return
				} else {
					uni.navigateTo({
						url: "/pages-sub/login/login",
					})
				}

				// this.isShow = true
				// uni.login({
				// 	provider: 'weixin',
				// 	success: res => {
				// 		console.log("res: " + JSON.stringify(res));
				// 		this.code = res.code

				// uni.getUserInfo({
				// 	success: (result) => {
				// 		console.log("result: " + JSON.stringify(
				// 			result));
				// 		console.log(res.code);
				// 		this.loginSys(res.code, result
				// 			.userInfo)
				// 	}
				// })


				// uni.request({
				// 	url: 'https://api.weixin.qq.com/sns/jscode2session', // 请求微信服务器
				// 	method: 'GET',
				// 	data: {
				// 		appid: 'wxe806e7db54b67752', //你的小程序的APPID
				// 		secret: '899cc1db4b6733c455cf3fec15517b9b', //你的小程序秘钥secret,  
				// 		js_code: res.code, //wx.login 登录成功后的code
				// 		grant_type: 'authorization_code' //此处为固定值
				// 	},
				// 	success: (res) => {
				// 		console.log('获取信息', res);
				// 		uni.getUserInfo({
				// 			success: (result) => {
				// 				console.log("res: " + JSON.stringify(
				// 					result));
				// 				console.log(res.data.unionid);
				// 				this.loginSys(res.data.unionid, result
				// 					.userInfo)
				// 			}
				// 		})
				// 	}
				// });

				// 	}
				// });
				// uni.navigateTo({
				// 	url: '/pages/information/information'
				// });
			},
			loginSys(code, info) {
				let _that = this
				// code是授权码，userinfo是小程序wx.getUserProfile
				// 接口返回的userInfo对象，inviter是邀请人的ID，如果没有就不填，userInfo和code是必填
				var params = {
					code: code,
					userInfo: {
						avatarUrl: info.avatarUrl ? info.avatarUrl : "",
						city: info.city ? info.city : "",
						country: info.country ? info.country : "",
						gender: info.gender ? info.gender : "",
						language: info.language ? info.language : "",
						nickName: info.nickName ? info.nickName : "",
						province: info.province ? info.province : "",
					},
					inviter: _that.inviter
				}
				console.log("------------------------" + _that.inviter);
				console.log("params: " + JSON.stringify(params));
				uni.request({
					url: 'https://superta.noboyun.com/api/teacher/auth',
					method: 'POST',
					data: params,
					header: {
						"Content-Type": "application/json",
					},
					success: (res) => {

						console.log("接口调用成功")
						console.log("res: " + JSON.stringify(res.data.data));
						uni.setStorageSync("token", res.data.data)
						// 获得用户信息
						_that.getInfo()

					},
					fail: (err) => {
						uni.showLoading({
							icon: "error",
							title: JSON.stringify(err)
						});
						setTimeout(function() {
							uni.hideLoading();
						}, 2000);
						console.log("调用接口失败")

					}
				})
			},
			formatData(data) {
				// 格式化用户信息
				const date = new Date(data.memberExpirationDate);
				const timeFormat = uni.$u.timeFormat;
				let timeValue = timeFormat(date, 'yyyy-mm-dd');
				return {
					id: data.id,
					openid: data.openid,
					avatar: data.avatar ? data.avatar : '',
					name: data.name ? data.name : "昵称",
					age: data.age,
					sex: data.sex,
					sexStr: data.sexStr,
					education: data.education,
					educationStr: data.educationStr,
					phoneNumber: data.phoneNumber,
					kindergartenName: data.kindergartenName,
					title: data.title,
					hobby: data.hobby,
					position: data.position,
					growthValue: data.growthValue,
					memberId: data.memberId,
					memberType: data.memberType,
					memberTypeStr: data.memberTypeStr,
					memberExpirationDate: timeValue,
					aiUseCount: data.aiUseCount,
				};
			},
			// 获得用户信息
			getInfo() {

				let _that = this

				const request1 = from(getTeacherInfo())
				const request2 = from(getCurrentBadge())
				const source = forkJoin([request1, request2])

				source.subscribe(([res1, res2]) => {
						this.loading = false;
						if (res1.data.id) {
							_that.updateUserInfo(res1.data)
						}
						if (res2.data) {
							this.updateBadge(res2.data.name)
						}
					},
					error => {

					},
					complete => {
						this.loading = false;
					}
				)
				source.pipe(
					timeout(500),
					finalize(() => {
						console.log('超时订阅结束');
					})
				).subscribe(
					res => {
						// 1秒内返回结果，输出
						this.loading = false;
						console.log('加载结束--', res);
					},
					err => {
						// 超时，输出
						this.loading = true;
						console.log('加载超时');
					}
				);



			},

			// 开通会员
			vipFn() {
				if (!this.hasLogin) {
					this.showRegister = true;
					return
				}
				uni.navigateTo({
					url: '/pages-sub/Vip/Vip'
				});
			},
			// 徽章
			badgeFn() {
				if (!this.hasLogin) {
					this.showRegister = true;
					return
				}
				uni.navigateTo({
					url: '/pages-sub/badge/badge'
				});
			},
			// 成长值
			growth() {
				if (!this.hasLogin) {
					this.showRegister = true;
					return
				}
				uni.navigateTo({
					url: '/pages-sub/growthValue/growthValue'
				});
			},
			transmit() {
				if (!this.hasLogin) {
					this.showRegister = true;
					return
				}
				uni.navigateTo({
					url: '/pages-sub/transmit/transmit'
				});
			}
		}
	};
</script>
<style lang="scss" scoped>
	.index-content {
		// min-height: calc(100vh);
		background-color: #f5f6fa;

		.information-top {
			padding: 0 30rpx;
			height: 100rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			position: absolute;

			.bg-bottom {
				position: fixed;
				left: 0;
				top: 0;
				z-index: 0;
				width: 100%;

				// height: 300px;
			}
		}

		.index-top {
			width: 100%;
			// height: 840rpx;
			// background: linear-gradient(179deg, #c6f6c3 0%, #ffffff 100%);

			position: relative;
			z-index: 990;
			top: 0;


			.head {
				width: 100%;
				display: flex;
				align-items: center;
				margin: 10rpx 40rpx;


				.logo {
					width: 128rpx;
					height: 128rpx;
					border-radius: 50%;
					background-size: 100%;
					border: 2rpx solid #fff;
				}

				.info {
					margin-left: 40rpx;

					.title {
						font-size: 40rpx;
						font-weight: 600;
						color: #3a3d4b;
					}

					.cid {
						height: 48rpx;
						border-radius: 24rpx;
						padding: 0rpx 20rpx;
						margin-top: 10rpx;
						background-color: #d8f3db;
						line-height: 48rpx;
						font-size: 24rpx;
						color: #27ab55;
					}
				}

				.arrow {
					flex: 1;
				}
			}

			.top-flex {
				// padding-top: 190rpx;
				display: flex;
				align-items: center;

			}

			.top-openMember {
				width: 686rpx;
				height: 128rpx;
				margin: 20rpx auto 0;
				background: url('../../static/icons/3.png');
				background-repeat: no-repeat;
				background-size: 100%;
				display: flex;
				justify-content: space-between;
				align-items: center;

				.left {
					// display: flex;
					margin-left: 28rpx;


					.left-icon {
						width: 40rpx;
						height: 40rpx;
						margin-right: 20rpx;
					}

					.left-title {
						margin-top: 5rpx;
						font-size: 32rpx;
						font-family: PingFangSC-Medium, PingFang SC;
						font-weight: 500;
						color: #ffe5be;
						line-height: 42rpx;
					}

					.left-text {
						margin-top: 5rpx;
						font-size: 24rpx;
						font-family: PingFangSC-Medium, PingFang SC;
						font-weight: 500;
						color: #ffe5be;
						line-height: 42rpx;
					}
				}


				.right {
					display: flex;
					justify-content: center;
					align-items: center;

					.invitation {
						width: 112rpx;
						height: 60rpx;
						border-radius: 30rpx;
						border: 2rpx solid #FEDBA0;
						color: #FEDBA0;

						font-size: 24rpx;
						font-family: PingFangSC, PingFang SC;
						font-weight: 400;
						color: #FEE1AE;
						line-height: 56rpx;
						text-align: center;

					}

					.openMember {
						margin-left: 20rpx;
						width: 152rpx;
						height: 56rpx;
						background: linear-gradient(100deg, #fce5bd 0%, #ffda9b 100%);
						border-radius: 28rpx;
						font-size: 24rpx;
						font-family: PingFangSC-Regular, PingFang SC;
						font-weight: 400;
						color: #434544;
						line-height: 56rpx;
						text-align: center;
						margin-right: 28rpx;
					}
				}

			}

			.top-myMedal {
				width: 750rpx;
				height: 224rpx;
				background: #ffffff;
				display: flex;
				justify-content: space-evenly;
				align-items: center;


				.myMedal-left {
					width: 328rpx;
					height: 160rpx;
					background: linear-gradient(315deg, #fffaf0 0%, #fff1dd 100%);
					background: url('../../static/icons/8.png');
					background-repeat: no-repeat;
					background-size: 100%;
					border-radius: 20rpx;

					.left-text {
						margin: 38rpx 180rpx 38rpx 28rpx;

						.left-textTop {
							font-size: 30rpx;
							font-family: PingFangSC-Medium, PingFang SC;
							font-weight: 500;
							color: #d18625;
						}

						.left-textBom {
							margin-top: 8rpx;
							font-size: 24rpx;
							font-family: PingFangSC-Regular, PingFang SC;
							font-weight: 400;
							color: #d18625;
						}
					}
				}

				.myMedal-right {
					width: 328rpx;
					height: 160rpx;
					background: linear-gradient(315deg, #e5fbf3 0%, #e7f9f3 100%);
					background: url('../../static/icons/8(1).png');
					background-repeat: no-repeat;
					background-size: 100%;
					border-radius: 20rpx;

					.right-text {
						margin: 38rpx 150rpx 38rpx 28rpx;

						.right-textTop {
							font-size: 30rpx;
							font-family: PingFangSC-Medium, PingFang SC;
							font-weight: 500;
							color: #30854c;

						}

						.right-textBom {
							font-size: 24rpx;
							margin-top: 8rpx;
							font-family: PingFangSC-Regular, PingFang SC;
							font-weight: 400;
							color: #30854c;
						}
					}
				}
			}
		}

		.index-list {
			background-color: #f5f6fa;
			margin-top: 20rpx;
			margin-bottom: 20rpx;
			position: relative;
			z-index: 1;

			.list-content {
				display: flex;

				background-color: #ffffff;
				margin-bottom: 20rpx;
				background-color: red;
			}

			.list-item {
				display: flex;
				align-items: center;
				height: 120rpx;
				background-color: #fff;
				border-bottom: 2rpx solid #f5f6fa;

				.icon {
					width: 40rpx;
					height: 40rpx;
					margin-left: 42rpx;

				}

				.text {
					padding-left: 20rpx;
					font-size: 30rpx;
					font-weight: 500;
					color: #273344;
				}

				.right {
					flex: 1;
					padding-right: 30rpx;
				}

			}
		}
	}

	::v-deep.u-icon {
		justify-content: flex-end;
	}
</style>